#!/usr/bin/env python

import sys
from tools import traceroute, ping
import pydot


graph = pydot.Dot(graph_type='digraph')
nodos = {}
colors = ["red", "green", "blue", "yellow", "brown", "black", "BlueViolet", "CadetBlue", "Darkorange", "DeepPink", "LightBlue", "Maroon", "Navy", "Turquoise", "YellowGreen"]

def newNode(addr):
	node = pydot.Node(addr)
	nodos[addr] = node		
	graph.add_node(node)

	return node
	
def getNode(addr):
	if addr in nodos.keys():
		node = nodos[addr]
	else:
		node = newNode(addr)
	return node

def getColor(n):
	return colors[n % len(colors)]


def run(hosts):
	
	infile = open(hosts)
	j = 0
	h = 0
	
	for univ in infile:
		if univ[0] == "#":
			continue
		
		h += 1
		
		if (len(univ.split("\t")) < 2):
			break
			
		host = univ.split("\t")[0]
		name = univ.split("\t")[1]
		
		r = ping(host)
		if r == None:
			continue
		
		ruta = traceroute(host)
		print "Ruta a " + host
		print ruta
		print "========"
		
		for i in range(0, len(ruta)-1):
			
			l1 = ruta[i]
			l2 = ruta[i+1]
			
			if "*" in ruta[i] and "*" in ruta[i+1]:
				continue
			
			if "*" in ruta[i]:
				l1  = "("+str(j)+")"+ruta[i]
			if "*" in ruta[i+1]:
				j += 1
				l2  = "("+str(j)+")"+ruta[i+1]
				
			
			n1 = getNode(l1)
			
			label = l2
			if i+1 == len(ruta)-1:
				label +=  " [" + host + "]"
			n2 = getNode(label)
			
			if i+1 == len(ruta)-1:
				n2.set_fillcolor(getColor(h))
				n2.set_color(getColor(h))
			
			graph.add_edge(pydot.Edge(n1, n2, color = getColor(h)))
	
			
	graph.write_png('graph.png')
	
	
if __name__ == "__main__":
	if len(sys.argv) < 2:
		print "experimento_traceroute.py [file entrada]"
		exit()
			
	run(sys.argv[1])
	
	
